package com.c1g19.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.log4j.Logger;

/**
 * 邮件发送操作类，用于邮件发送
 * 
 * @author user
 * 
 */
public class SendMail {
	private static String username = PropertyManager
			.getProperty("email_account");
	private static String password = PropertyManager
			.getProperty("email_password");
	private static String smtpServer = PropertyManager
			.getProperty("email_server");
	private static String fromMailAddress = PropertyManager
			.getProperty("from_email_address");

	private static final Logger logger = Logger.getLogger(SendMail.class);

	/**
	 * 发送普通邮件
	 * 
	 * @param subject
	 *            邮件主题
	 * @param content
	 *            邮件内容
	 * @param toMailAddress
	 *            邮件接收者
	 * @throws Exception
	 */
	public static void sendSimpleEmail(String subject, String content,
			String toMailAddress) {
		logger.info("[发送邮件]" + toMailAddress + ":" + content);

		try {
			Properties props = new Properties();
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.host", smtpServer);
			// 获得邮件会话对象
			Session session = Session.getDefaultInstance(props,
					new SmtpAuthenticator(username, password));
			/** *************************************************** */
			// 创建MIME邮件对象
			MimeMessage mimeMessage = new MimeMessage(session);
			mimeMessage.setFrom(new InternetAddress(fromMailAddress));// 发件人
			mimeMessage.setRecipients(Message.RecipientType.TO, toMailAddress);
			mimeMessage.setSubject(subject);
			mimeMessage.setSentDate(new Date());// 发送日期
			Multipart mp = new MimeMultipart("related");// related意味着可以发送html格式的邮件
			/** *************************************************** */
			BodyPart bodyPart = new MimeBodyPart();// 正文
			bodyPart.setDataHandler(new DataHandler(content,
					"text/html;charset=UTF-8"));// 网页格式
			/** *************************************************** */
			mp.addBodyPart(bodyPart);
			mimeMessage.setContent(mp);// 设置邮件内容对象
			Transport.send(mimeMessage);// 发送邮件
		} catch (Exception e) {
			logger.error("", e);
		}

	}

	/**
	 * 发送带附件的邮件
	 * 
	 * @param subject
	 *            邮件主题
	 * @param content
	 *            邮件内容
	 * @param toMailAddress
	 *            发送到邮箱号码
	 * @param attachFile
	 *            附件地址，完整的路径
	 * @throws Exception
	 */
	public static void sendEmail(String subject, String content,
			String toMailAddress, String attachFile) {
		logger.info("[发送邮件]" + toMailAddress + ":" + content);
		try {
			Properties props = new Properties();
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.host", smtpServer);
			// 获得邮件会话对象
			Session session = Session.getDefaultInstance(props,
					new SmtpAuthenticator(username, password));
			/** *************************************************** */
			// 创建MIME邮件对象
			MimeMessage mimeMessage = new MimeMessage(session);
			mimeMessage.setFrom(new InternetAddress(fromMailAddress));// 发件人
			mimeMessage.setRecipient(Message.RecipientType.TO,
					new InternetAddress(toMailAddress));// 收件人
			mimeMessage.setSubject(subject);
			mimeMessage.setSentDate(new Date());// 发送日期
			Multipart mp = new MimeMultipart("related");// related意味着可以发送html格式的邮件
			/** *************************************************** */
			/*
			 * BodyPart bodyPart = new MimeBodyPart();// 正文
			 * bodyPart.setDataHandler(new
			 * DataHandler(content,"text/html;charset=UTF-8"));// 网页格式
			 * mp.addBodyPart(bodyPart);
			 */
			MimeBodyPart bodyPart = new MimeBodyPart();// 正文
			bodyPart.setContent(content, "text/html;charset=UTF-8");// 网页格式
			mp.addBodyPart(bodyPart);
			/** *************************************************** */
			BodyPart attachBodyPart = new MimeBodyPart();// 普通附件
			FileDataSource fds = new FileDataSource(attachFile);
			attachBodyPart.setDataHandler(new DataHandler(fds));
			attachBodyPart.setFileName(MimeUtility.encodeText(fds.getName()));
			mp.addBodyPart(attachBodyPart);
			/** *************************************************** */
			mimeMessage.setContent(mp);// 设置邮件内容对象
			Transport.send(mimeMessage);// 发送邮件
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	/**
	 * 发送带附件的邮件
	 * 
	 * @param subject
	 *            邮件主题
	 * @param content
	 *            邮件内容
	 * @param toMailAddress
	 *            发送到邮箱号码
	 * @param attachFile
	 *            附件地址，完整的路径
	 * @throws Exception
	 */
	public static void sendEmail(String subject, String content,
			String toMailAddress, List<String> attachFileList) {
		logger.info("[发送邮件]" + toMailAddress + ":" + content);
		try {
			Properties props = new Properties();
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.host", smtpServer);
			// 获得邮件会话对象
			Session session = Session.getDefaultInstance(props,
					new SmtpAuthenticator(username, password));
			/** *************************************************** */
			// 创建MIME邮件对象
			MimeMessage mimeMessage = new MimeMessage(session);
			mimeMessage.setFrom(new InternetAddress(fromMailAddress));// 发件人
			mimeMessage.setRecipient(Message.RecipientType.TO,
					new InternetAddress(toMailAddress));// 收件人
			mimeMessage.setSubject(subject);
			mimeMessage.setSentDate(new Date());// 发送日期
			Multipart mp = new MimeMultipart("related");// related意味着可以发送html格式的邮件
			/** *************************************************** */
			/*
			 * BodyPart bodyPart = new MimeBodyPart();// 正文
			 * bodyPart.setDataHandler(new
			 * DataHandler(content,"text/html;charset=UTF-8"));// 网页格式
			 * mp.addBodyPart(bodyPart);
			 */
			MimeBodyPart bodyPart = new MimeBodyPart();// 正文
			bodyPart.setContent(content, "text/html;charset=UTF-8");// 网页格式
			mp.addBodyPart(bodyPart);
			/** *************************************************** */
			for (String attachFile : attachFileList) {
				BodyPart attachBodyPart = new MimeBodyPart();// 普通附件
				FileDataSource fds = new FileDataSource(attachFile);
				attachBodyPart.setDataHandler(new DataHandler(fds));
				attachBodyPart.setFileName(MimeUtility
						.encodeText(fds.getName()));
				mp.addBodyPart(attachBodyPart);
			}
			/** *************************************************** */
			mimeMessage.setContent(mp);// 设置邮件内容对象
			Transport.send(mimeMessage);// 发送邮件
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	/**
	 * 读取文件
	 * 
	 * @param file
	 *            文件路径
	 * @return 返回二进制数组
	 */
	private static byte[] readFile(String file) {
		FileInputStream fis = null;
		ByteArrayOutputStream bos = null;
		try {
			fis = new FileInputStream(file);
			bos = new ByteArrayOutputStream();
			int bytesRead;
			byte buffer[] = new byte[1024 * 1024];
			while ((bytesRead = fis.read(buffer)) != -1) {
				bos.write(buffer, 0, bytesRead);
				Arrays.fill(buffer, (byte) 0);
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			try {
				if (bos != null)
					bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return bos.toByteArray();
	}

	public static void main(String[] args) {
		try {
			// SendMail.sendEmail("this is test 1 attach",
			// "1个附件","zero.xu@sinocontact.com","d:\\ef\\leadsReport\\adult\\a.xls");
			/*
			 * List<String> fileList=new ArrayList<String>();
			 * fileList.add("d:\\ef\\leadsReport\\adult\\a.xls");
			 * fileList.add("d:\\ef\\leadsReport\\adult\\v.xls");
			 * SendMail.sendEmail("this is test 2 attach",
			 * "2个附件","zero.xu@sinocontact.com",fileList);
			 */
			String beginDate = "2015-09-05";
			int totalNum = 1;
			// String toMailAddress="zero.xu@sinocontact.com";
			String toMailAddress = "Summer.Xiaying@EF.com";

			String destFileName = "d:\\ef\\leadsReport\\adult\\test.xls";
			SendMail
					.sendEmail(
							"Zero Test Email 1",
							"<span style='font-size:14px'><i>Data Period: "
									+ beginDate.replaceAll("-", "/")
									+ "</i>"
									+ "<br/><br/>Download attachment to see the leads list during above data period.<br/>"
									+ "<span style='color:#EC008C;font-size:1.2em'>"
									+ totalNum
									+ "</span> new leads in total.<br/><br/>"
									+ "If you have any question, please contact iWOM team via email (iWOM.cn@ef.com).<br/><br/>"
									+ "Best Regards,<br/>"
									+ "Central iWOM & Social Media Team<br/><br/>"
									+ "<span style='font-size:0.9em'>**Please do not respond to this automated message, as no replies are available from this email address.**</span></span>",
							toMailAddress, destFileName);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

/**
 * Smtp认证
 */
class SmtpAuthenticator extends Authenticator {
	String username = null;
	String password = null;

	// SMTP身份验证
	public SmtpAuthenticator(String username, String password) {
		this.username = username;
		this.password = password;
	}

	public PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(this.username, this.password);
	}

}

class ByteArrayDataSource implements DataSource {

	private final String contentType;
	private final byte[] buf;
	private final int len;

	public ByteArrayDataSource(byte[] buf, String contentType) {
		this(buf, buf.length, contentType);
	}

	public ByteArrayDataSource(byte[] buf, int length, String contentType) {
		this.buf = buf;
		this.len = length;
		this.contentType = contentType;
	}

	public String getContentType() {
		if (contentType == null)
			return "application/octet-stream";
		return contentType;
	}

	public InputStream getInputStream() {
		return new ByteArrayInputStream(buf, 0, len);
	}

	public String getName() {
		return null;
	}

	public OutputStream getOutputStream() {
		throw new UnsupportedOperationException();
	}

}
